package com.augurit.smartform.database.dialect;

import java.util.HashMap;

import com.augurit.common.util.lang.StringUtils;

public class TypeNames {
	private HashMap defaults = new HashMap();
	
	public void put(String typecode, String value) {
		defaults.put( typecode, value );
	}
	
	public String get(String typecode) throws RuntimeException {
		String result = (String) defaults.get( typecode );
		if (result==null) throw new RuntimeException("No Dialect mapping for JDBC type: " + typecode);
		return result;
	}
	
	/**
	 * get type name for specified type and size
	 * @param typecode the type key
	 * @param size the SQL length
	 * @param scale the SQL scale
	 * @param precision the SQL precision
	 * @return the associated name with smallest capacity >= size,
	 * if available and the default type name otherwise
	 */
	public String get(String typecode, int size, int precision, int scale) throws RuntimeException {
		return replace( get(typecode), size, precision, scale );
	}
	
	private static String replace(String type, int size, int precision, int scale) {
		type = StringUtils.replaceOnce(type, "$s", Integer.toString(scale) );
		type = StringUtils.replaceOnce(type, "$l", Integer.toString(size) );
		return StringUtils.replaceOnce(type, "$p", Integer.toString(precision) );
	}
}
